<template>
  <div class="gk-layout-container">
    <div class="gk-layout-header">
      <!--工具栏-->
      <s-query perms="material:classify" @click="findPage" add=true @addClick="handleAdd">
        <el-form-item>
          <el-input v-model="filters.name" :placeholder="$t('classify.please enter')"></el-input>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" style="width:100;height: 20;" @click="updateStock">更新库存物料分类</el-button>
        </el-form-item>
      </s-query>
      <s-reflash reflash="true" @findPage="findPage"> </s-reflash>

    </div>
    <!--表格内容栏-->
    <div class="gk-layout-main">
      <my-table :data="pageResult.content" :loading="loading" @selection-change="selectionChange">
        <el-table-column :label="$t('action.desc')" width="50" header-align="center" align="center">
          <template slot-scope="scope"> {{ scope.$index + 1 }} </template>
        </el-table-column>
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column header-align="center" align="center" width="300" prop="name" :label="$t('classify.name')"
          key="name"> </el-table-column>
        <el-table-column header-align="center" align="center" prop="info" :label="$t('classify.info')" key="info">
        </el-table-column>
        <el-table-column header-align="center" align="center" prop="id" :label="$t('classify.Id')" key="id">
        </el-table-column>
        <el-table-column header-align="center" align="center" :label="$t('action.operation')">
          <template slot-scope="scope">
            <kt-delete-button perms="material:classify:delete" @click="handleDelete(scope.$index, scope.row)" />
            <kt-button :label="$t('action.edit')" perms="material:classify:edit"
              @click="handleEdit(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </my-table>
    </div>
    <!--分页栏-->
    <div class="toolbar gk-layout-footer" style="padding:10px;">
      <kt-delete-button perms="material:classify:delete" @click="handleBatchDelete()" disable style="float:left;"
        :disabled="this.selections.length == 0" />
      <kt-button icon="fa fa-chain" label="" perms="material:classify:setarea" style="float:left;" type="primary"
        @click="handleBatchSet" />

      <el-pagination layout="total, prev, pager, next, jumper" @current-change="findPage" :current-page="filters.pageNum"
        :page-size="filters.pageSize" :total="pageResult.totalSize" style="float:right;">
      </el-pagination>
    </div>




    <!--新增编辑界面-->
    <el-dialog :title="operation ? '物料类别 —— 新增' : '物料类别 —— 编辑'" width="40%" :visible.sync="dialogVisible"
      :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="90px" :rules="dataFormRules" ref="dataForm" :size="global.gSize"
        label-position="right">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('classify.name')" prop="name">
          <el-input v-model="dataForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('classify.info')" prop="info">
          <el-input v-model="dataForm.info" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="global.gSize" @click.native="dialogVisible = false">{{ $t('action.cancel') }}</el-button>
        <el-button :size="global.gSize" type="primary" @click.native="submitForm" :loading="editLoading">{{
          $t('action.submit') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="operation ? '设置库区 —— 批量编辑' : $t('action.edit')" width="30%" :visible.sync="dialogVisibles"
      :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="100px" :rules="dataFormRules" ref="dataForm" :size="global.gSize"
        label-position="right">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('field.Core.corewhloc.areaName')" prop="areaId">
          <el-select v-model="dataForm.areaId" placeholder="请选择" auto-complete="off" style="width: 100%;" clearable
            filterable>
            <el-option v-for="item in areaTypes" :key="item.id" :label="item.areaName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <s-dict-form name="eigen" v-model="dataForm.eigen"> </s-dict-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="global.gSize" @click.native="dialogVisibles = false">{{ $t('action.cancel') }}</el-button>
        <el-button :size="global.gSize" type="primary" @click.native="submitForms" :loading="editLoading">
          {{ $t('action.submit') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput"
import SDictForm from "@/components/Kj/SDictForm"
import KtButton from "@/views/Core/KtButton"
import KtDeleteButton from "@/views/Core/KtDeleteButton"
import MyTable from "@/views/Core/MyTable"
import SQuery from "@/components/Kj/SQuery"
import SReflash from "@/components/Kj/SReflash"
import { format } from "@/utils/datetime"
export default {
  components: {
    PopupTreeInput,
    MyTable,
    KtButton,
    KtDeleteButton,
    SReflash, SQuery, SDictForm
  },
  data() {
    return {

      filters: {
        name: '', pageNum: 1, pageSize: this.global.pageSize
      },
      loading: false,

      demo: [],
      pageResult: {},
      dicts: [],
      operation: false, // true:新增, false:编辑
      dialogVisible: false,
      dialogVisibles: false,// 设置区位界面是否显示
      editLoading: false,
      selections: [],
      // 新增编辑界面数据
      dataForm: {
        id: 0,
        name: '',
        info: '',
        stockWidth: 0,
        stockHigh: 0,
        stockDeep: 0,
        areaId: "",
        eigen: 0
      },
      areaTypes: []
    }
  },
  computed: {
    dataFormRules() {
      const dataFormRules = {
        name: [{ required: true, message: this.getKey("user.userInput"), trigger: 'blur' }],
        areaId: [{ required: true, message: "请选择区域名称", trigger: 'blur' }]
      };
      return dataFormRules;
    }
  },
  methods: {
    // 获取分页数据
    findPage: function (data) {
      if (data != -1) {
        this.filters.pageNum = data
      }

      this.$api.classify.findPage(this.filters).then((res) => {
        this.pageResult = res.data

      })
    },

    findAreaTypes: function () {
      this.$api.corewharea.findPage().then((res) => {
        this.areaTypes = res.data.content
      })
    },
    updateStock: function (data) {
      this.$confirm('确定更新库存物料分类吗？', '提示', {}).then(() => {
        this.$api.classify.updateStock(this.filters).then(res => {
          if (res.code = 200) {
            this.$message({ message: this.$t('action.operateSucess'), type: 'success' })
          }
          else {
            this.$message({ message: this.$t('action.operateFail') + res.msg, type: 'error' })
          }
        })
      })
    },

    //批量编辑
    submitForms: function () {
      if (!this.selections || this.selections.length == 0) {
        this.$message({ message: "请至少选择一条数据", type: 'error' })
        return;
      }
      let ppa = [];
      for (var i = 0; i < this.selections.length; i++) {
        ppa.push(this.selections[i].id)
      }
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm(this.getKey('action.isConfirm'), this.getKey('action.tips'), {}).then(() => {
            this.editLoading = true
            let params = this.dataForm.areaId + "/" + this.dataForm.eigen
            this.$api.classify.batchset(ppa, params).then((res) => {
              this.editLoading = false
              if (res.code == 200) {
                this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
                this.dialogVisibles = false
                this.$refs['dataForm'].resetFields()
              } else {
                this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
              }
              this.findPage(-1)
            })
          })
        }
      })
    },

    //显示批量设置库位界面
    handleBatchSet: function () {
      this.dialogVisibles = true
      this.operation = true
      this.demo = this.selections;
      console.log(this.demo);
    },



    findUserRoles: function () {
      this.$api.role.findAll().then((res) => {
        // 加载角色集合
        this.roles = res.data
      })
    },
    selectionChange: function (selection) {
      this.selections = selection;
    },
    handleBatchDelete: function () {
      let ids = this.selections.map(item => item.id).toString()
      let params = []
      let idArray = (ids + '').split(',')
      for (var i = 0; i < idArray.length; i++) {
        params.push({ 'id': idArray[i] })
      }
      this.$api.classify.batchDelete(params).then((res) => {
        if (res.code == "500") {

          this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
        }
        this.findPage(-1)
      });
    },
    // 批量删除
    handleDelete: function (index, data) {

      let params = [{ 'id': data.id }]

      this.$api.classify.batchDelete(params).then((res) => {
        if (res.code == "500") {

          this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
        }
        this.findPage(-1)
      });
    },

    // 显示新增界面
    handleAdd: function () {
      this.dialogVisible = true
      this.operation = true
      this.dataForm = {
        id: 0,
        name: '',
        info: '',
        stockWidth: 0,
        stockHigh: 0,
        stockDeep: 0
      }
    },
    // 显示编辑界面
    handleEdit: function (index, row) {
      this.dialogVisible = true
      this.operation = false
      this.dataForm = Object.assign({}, row)
    },
    // 编辑
    submitForm: function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm(this.getKey('action.isConfirm'), this.getKey('action.tips'), {}).then(() => {
            this.editLoading = true
            let params = Object.assign({}, this.dataForm)
            this.$api.classify.save(params).then((res) => {
              this.editLoading = false
              if (res.code == 200) {
                this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
                this.dialogVisible = false
                this.$refs['dataForm'].resetFields()
              } else {
                this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
              }
              this.findPage(-1)
            })
          })
        }
      })
    },
    // 获取部门列表
    findDeptTree: function () {
      this.$api.dept.findDeptTree().then((res) => {
        this.deptData = res.data
      })
    },
    // 菜单树选中
    deptTreeCurrentChangeHandle(data, node) {
      this.dataForm.deptId = data.id
      this.dataForm.deptName = data.name
    },
    // 时间格式化
    dateFormat: function (row, column, cellValue, index) {
      return format(row[column.property])
    },


    getKey: function (arg) {
      return this.$t(arg)
    },

    selectionFormat: function (row, column, cellValue, index) {
      let key = ""
      let propt = column.property;
      let val = row[column.property];
      let dict = this.areaTypes;
      for (let i = 0; i < dict.length; i++) {
        if (dict[i].id == val) {
          return dict[i].areaName;
        }
      }
      return row[column.property]
    },
  },
  created() {

    this.findAreaTypes();
    this.findPage(1);
  },
  watch: {

    dialogVisible(to, from) {
      if (this.$refs['dataForm'] !== undefined) {
        this.$refs["dataForm"].resetFields();
      }
    }
  }

}
</script>

<style scoped></style>